package com.ruitaowang.admin.view.api;

import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.account.service.SysUserService;
import com.ruitaowang.account.service.WalletService;
import com.ruitaowang.core.domain.*;
import com.ruitaowang.core.utils.EmojiFilter;
import com.ruitaowang.core.utils.StringUtils4RT;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import wx.wechat.service.mp.MPService;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;

/**
 * Created by neal on 11/17/16.
 */
@RestController
public class APIActivityController extends BaseController {

    protected final Logger LOGGER = LoggerFactory.getLogger(getClass());

    @Autowired
    private ActivityService activityService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderProdService orderProdService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private UserMembersService userMembersService;
    @Autowired
    private RelationsService relationService;
    @Autowired
    private UserProfitService userProfitService;
    @Autowired
    private MzAdsService mzAdsService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private LocalOrderService localOrderService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private CompanyTypeService companyTypeService;
    @Autowired
    private CompanyIndustryService companyIndustryService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private WXUserinfoService wxUserinfoService;

    /**
     * @api {get} /api/activities 分页获取活动或者广告列表
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/activities
     * @apiName findActivityPage
     * @apiGroup Activity
     * @apiParam {int} page 第几页.
     * @apiParam {int} rows 每页条数.
     * @apiParam {int} activityType 活动类型.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":[
     * {
     * "activityAuthor":1,
     * "activityId":719,
     * "activityImageUrl":"http://static.ruitaowang.com/attached/file/20170522/20170522185933_400.jpeg",
     * "activitySort":0,
     * "activityTitle":"你旅游我买单",
     * "activityType":0,
     * "activityUrl":"https://www.ruitaowang.com/wap/wx/login?fk=1-15-0-718",
     * "ctime":1495450727557,
     * "goodsId":0,
     * "mtime":1495461867633,
     * "rstatus":0
     * }
     * ],
     * "msg":"操作成功啦",
     * "records":5,
     * "title":"成功",
     * "total":1,
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/activities"
     * }
     */
//    @RequestMapping("/api/activities")
//    public String findActivityPage(Activity activity, int page) {
//        activity.setPage(page);
//        MsgOut o = MsgOut.success(activityService.selectForPage(activity));
//        o.setRecords(activity.getRecords());
//        o.setTotal(activity.getTotal());
//        return this.renderJson(o);
//    }

    @RequestMapping("/api/activities")
    public String findActivityPage(Activity activity, int page) {
        activity.setPage(page);
        List<ActivityVo> activityVos=new ArrayList<>();
        List<Activity> activities = activityService.selectForPage(activity);
        for(Activity  a: activities){
            ActivityVo activityVo=new ActivityVo();
            BeanUtils.copyProperties(a,activityVo);
            activityVos.add(activityVo);
        }
        MsgOut o = MsgOut.success(activityVos);
        o.setRecords(activity.getRecords());
        o.setTotal(activity.getTotal());
        return this.renderJson(o);
    }

    @RequestMapping("/api/wap/activities")
    public String wapFindActivity(Activity activity) {
        if (ObjectUtils.isEmpty(activity)) {
            return this.renderJson(MsgOut.error("no data."));
        }
        List listOut=new ArrayList();
        HashMap map = new HashMap();
        if (activity.getActivityType() == 11 || activity.getActivityType() == 12 || activity.getActivityType() == 13) {
            activity.setActivityType((byte) 11);
            List<Activity> activities11 = activityService.selectForPage(activity);
            if (!ObjectUtils.isEmpty(activities11)) {
                map.put("activity11", activities11);
            } else {
                map.put("activity11", "");
            }
            activity.setActivityType((byte) 12);
            List<Activity> activities12 = activityService.selectForPage(activity);
            if (!ObjectUtils.isEmpty(activities12)) {
                map.put("activity12", activities12);
            } else {
                map.put("activity12", "");
            }
            activity.setActivityType((byte) 13);
            List<Activity> activities13 = activityService.selectForPage(activity);
            if (!ObjectUtils.isEmpty(activities13)) {
                map.put("activity13", activities13);
            } else {
                map.put("activity13", "");
            }
            listOut.add(map);
        }else {
            List<Activity> activities = activityService.selectForPage(activity);
            listOut.add(activities);
        }
        MsgOut o = MsgOut.success(listOut);
        o.setRecords(activity.getRecords());
        o.setTotal(activity.getTotal());
        return this.renderJson(o);
    }


    /**
     * @api {post} /api/activities 创建活动
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/activities
     * @apiPermission admin
     * @apiName createActivity
     * @apiGroup Activity
     * @apiParam {long} activityId 活动编号.
     * @apiParam {long} activityAuthor 创建者编号.
     * @apiParam {int} activityType 活动类型.
     * @apiParam {string} activityTitle 活动标题.
     * @apiParam {string} activityImageUrl 活动封面图片地址.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":
     * {
     * "activityAuthor":1,
     * "activityId":719,
     * "activityImageUrl":"http://static.ruitaowang.com/attached/file/20170522/20170522185933_400.jpeg",
     * "activitySort":0,
     * "activityTitle":"你旅游我买单",
     * "activityType":0,
     * "activityUrl":"https://www.ruitaowang.com/wap/wx/login?fk=1-15-0-718",
     * "ctime":1495450727557,
     * "goodsId":0,
     * "mtime":1495461867633,
     * "rstatus":0
     * },
     * "msg":"操作成功啦",
     * "records":5,
     * "title":"成功",
     * "total":1,
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/activities"
     * }
     */
    @RequestMapping(value = "/api/activities", method = RequestMethod.POST)
    public String createActivity(Activity activity) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (!ObjectUtils.isEmpty(user)) {
            activity.setActivityAuthor(user.getId());
        }
        activityService.insert(activity);
        MsgOut o = MsgOut.success(activity);
        return this.renderJson(o);
    }

//    @RequestMapping(value = "/api/mzTest/test", method = RequestMethod.GET)
//    public String mzTest() {
//        Long orderId = 32L;
//        Double overall_profit_1_level = 0.3;
//        Double overall_profit_2_level = 0.15;
//        Double overall_reward_1_level = 0.03;
//        Double overall_reward_2_level = 0.015;
//        Double overall_profit_myself_level = 0.1;
//
//        Byte profit_type_rtshop_level1_money = 1;
//        Byte profit_type_rtshop_level2_money = 2;
//        Byte profit_type_rtshop_reward1_money = 3;
//        Byte profit_type_rtshop_reward2_money = 4;
//        Byte profit_type_rtshop_myself_money = 0;
//
//        // 检测重复返利限制
//        LocalOrder localOrder = localOrderService.selectByPK(orderId);
//
//
//        int profitForTotal = 0;
//        int profitType = 0;
//        int companyCommission = 0;
//        profitType = 1;
//        profitForTotal = localOrder.getPrice() - localOrder.getScore();
//        System.out.println("1-----" + profitForTotal);
//        Company company = companyService.selectByPK(localOrder.getCompanyId());
//
//        if (company.getCompanyTypeId() != 0) {
//            CompanyType companyType = companyTypeService.selectByPK(company.getCompanyTypeId());
//            if (!ObjectUtils.isEmpty(companyType)) {
//                CompanyIndustry companyIndustry = companyIndustryService.selectByPK(companyType.getIndustryId());
//                companyCommission = companyIndustry.getCompanyCommission();
//            }
//        }
//        if (companyCommission != 0) {
//            profitForTotal = (profitForTotal * companyCommission) / 100;
//        }
//        System.out.println("2-----" + profitForTotal);
//        List<Long> parents = relationService.selectAllParents(localOrder.getUserId());
//        if (!ObjectUtils.isEmpty(parents) && parents.size() > 1 && companyCommission != 0) {
//            Collections.reverse(parents);
//            int len = parents.size();
//            len = len >= 3 ? 3 : len;//只取两级
//            int level1 = (int) (profitForTotal * overall_profit_1_level);
//            int level2 = (int) (profitForTotal * overall_profit_2_level);
//            int reward1 = (int) (profitForTotal * overall_reward_1_level);
//            int reward2 = (int) (profitForTotal * overall_reward_2_level);
//            int myself = (int) (profitForTotal * overall_profit_myself_level);
//            System.out.println(level1 + "--" + level2 + "--" + reward1 + "--" + reward2 + "--" + myself);
//            //购买者返利红包
//            walletService.createUserProfitForScore(localOrder.getUserId(), myself);
//            setUserProfitNew(localOrder.getOrderSn(), localOrder.getUserId(), localOrder.getPrice(), localOrder.getUserId(), localOrder.getOrderId(), myself, profitType, profit_type_rtshop_myself_money);
//            //一级红包
//            for (int i = 1; i < len; i++) {
//                if (i == 1) {
//                    walletService.createUserProfit(parents.get(i), level1);
//                    setUserProfitNew(localOrder.getOrderSn(), parents.get(i), localOrder.getPrice(), localOrder.getUserId(), localOrder.getOrderId(), level1, profitType, profit_type_rtshop_level1_money);
//                    if (!ObjectUtils.isEmpty(parents.get(i))) {
//                        List<Long> parentList = relationService.selectAllParents(parents.get(i));
//                        if (!ObjectUtils.isEmpty(parentList) && parentList.size() > 1) {
//                            Collections.reverse(parentList);
//                            int parentListLen = parents.size();
//                            parentListLen = parentListLen >= 3 ? 3 : parentListLen;//只取两级
//                            for (int s = 1; s < parentListLen; s++) {
//                                //一级 奖励金
//                                if (s == 2) {
//                                    walletService.createUserProfit(parentList.get(s), reward1);
//                                    setUserProfitNew(localOrder.getOrderSn(), parentList.get(s), localOrder.getPrice(), localOrder.getUserId(), localOrder.getOrderId(), reward1, profitType, profit_type_rtshop_reward1_money);
//                                }
//                            }
//                        }
//                    }
//                }
//                //二级红包
//                if (i == 2) {
//                    walletService.createUserProfit(parents.get(i), level2);
//                    setUserProfitNew(localOrder.getOrderSn(), parents.get(i), localOrder.getPrice(), localOrder.getUserId(), localOrder.getOrderId(), level2, profitType, profit_type_rtshop_level2_money);
//                    if (!ObjectUtils.isEmpty(parents.get(i))) {
//                        List<Long> parentList = relationService.selectAllParents(parents.get(i));
//                        if (!ObjectUtils.isEmpty(parentList) && parentList.size() > 1) {
//                            Collections.reverse(parentList);
//                            int parentListLen = parents.size();
//                            parentListLen = parentListLen >= 3 ? 3 : parentListLen;//只取两级
//                            for (int s = 1; s < parentListLen; s++) {
//                                //二级 奖励金
//                                if (s == 2) {
//                                    walletService.createUserProfit(parentList.get(s), reward2);
//                                    setUserProfitNew(localOrder.getOrderSn(), parentList.get(s), localOrder.getPrice(), localOrder.getUserId(), localOrder.getOrderId(), reward2, profitType, profit_type_rtshop_reward2_money);
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//        }
//        MsgOut out = MsgOut.success("1");
//        return this.renderJson(out);
//    }

    /**
     * @api {put} /api/activities 更新活动
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/activities
     * @apiPermission admin
     * @apiName updateActivity
     * @apiGroup Activity
     * @apiParam {long} activityId 活动编号.
     * @apiParam {long} activityAuthor 创建者编号.
     * @apiParam {int} activityType 活动类型.
     * @apiParam {string} activityTitle 活动标题.
     * @apiParam {string} activityImageUrl 活动封面图片地址.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":
     * {
     * "activityAuthor":1,
     * "activityId":719,
     * "activityImageUrl":"http://static.ruitaowang.com/attached/file/20170522/20170522185933_400.jpeg",
     * "activitySort":0,
     * "activityTitle":"你旅游我买单",
     * "activityType":0,
     * "activityUrl":"https://www.ruitaowang.com/wap/wx/login?fk=1-15-0-718",
     * "ctime":1495450727557,
     * "goodsId":0,
     * "mtime":1495461867633,
     * "rstatus":0
     * },
     * "msg":"操作成功啦",
     * "records":5,
     * "title":"成功",
     * "total":1,
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/activities"
     * }
     */
    @RequestMapping(value = "/api/activities", method = RequestMethod.PUT)
    public String updateActivity(Activity activity) {
        activity.setActivityContent(EmojiFilter.filterEmoji(activity.getActivityContent()));
        activityService.update(activity);
        MsgOut o = MsgOut.success(activity);
        return this.renderJson(o);
    }

    /**
     * @api {delete} /api/activities/:activityId 删除活动
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/activities/:activityId
     * @apiPermission admin
     * @apiName deleteActivity
     * @apiGroup Activity
     * @apiParam {long} activityId 活动编号.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":1,
     * "msg":"操作成功啦",
     * "records":5,
     * "title":"成功",
     * "total":1,
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/activities"
     * }
     */
    @RequestMapping(value = "/api/activities/{activityId}", method = RequestMethod.DELETE)
    public String deleteActivity(@PathVariable("activityId") Long activityId) {

        MsgOut o = MsgOut.success(activityService.delete(activityId));
        return this.renderJson(o);
    }

    /**
     * @api {get} /api/activities/:activityId 获取指定活动
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/activities/:activityId
     * @apiName findOne
     * @apiGroup Activity
     * @apiParam {long} activityId 活动编号.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":
     * {
     * "activityAuthor":1,
     * "activityId":719,
     * "activityImageUrl":"http://static.ruitaowang.com/attached/file/20170522/20170522185933_400.jpeg",
     * "activitySort":0,
     * "activityTitle":"你旅游我买单",
     * "activityType":0,
     * "activityUrl":"https://www.ruitaowang.com/wap/wx/login?fk=1-15-0-718",
     * "ctime":1495450727557,
     * "goodsId":0,
     * "mtime":1495461867633,
     * "rstatus":0
     * },
     * "msg":"操作成功啦",
     * "records":5,
     * "title":"成功",
     * "total":1,
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/activities"
     * }
     */
    @RequestMapping(value = "/api/activities/{activityId}", method = RequestMethod.GET)
    public String findOne(@PathVariable("activityId") Long activityId) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        HashMap map = new HashMap();
        Activity activity = activityService.selectByPK(activityId);
        SysUser sysUser = sysUserService.selectByPK(user.getId());
        map.put("activity", activity);
        map.put("sysUser", sysUser);
        MsgOut o = MsgOut.success(map);
        return this.renderJson(o);
    }
    @RequestMapping(value = "/api/wap/activities/{activityId}", method = RequestMethod.GET)
    public String wapFindOne(@PathVariable("activityId") Long activityId,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }

        Activity activity = activityService.selectByPK(activityId);
        MsgOut o = MsgOut.success(activity);
        return this.renderJson(o);
    }

    /**
     * @api {get} /api/activities/:activityId 获取指定活动
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/activities/:activityId
     * @apiName findOne
     * @apiGroup Activity
     * @apiParam {long} activityId 活动编号.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":
     * {
     * "activityAuthor":1,
     * "activityId":719,
     * "activityImageUrl":"http://static.ruitaowang.com/attached/file/20170522/20170522185933_400.jpeg",
     * "activitySort":0,
     * "activityTitle":"你旅游我买单",
     * "activityType":0,
     * "activityUrl":"https://www.ruitaowang.com/wap/wx/login?fk=1-15-0-718",
     * "ctime":1495450727557,
     * "goodsId":0,
     * "mtime":1495461867633,
     * "rstatus":0
     * },
     * "msg":"操作成功啦",
     * "records":5,
     * "title":"成功",
     * "total":1,
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/activities"
     * }
     */
    @RequestMapping(value = "/api/mz2/activities/{activityId}", method = RequestMethod.GET)
    public String findTwo(@PathVariable("activityId") Long activityId) {
        Activity activity = activityService.selectByPK(activityId);
        MsgOut o = MsgOut.success(activity);
        return this.renderJson(o);
    }

    /**
     * @api {get} /api/activities/preNextActivity 龙蛙官网上一页下一页
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/preNextActivity
     * @apiName listForOffice
     * @apiGroup Activity
     * @apiParam {string} activityId 活动编号.
     * @apiParam {string} activityType 活动类型.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":[
     * {
     * "activityAuthor":1,
     * "activityId":719,
     * "activityImageUrl":"http://static.ruitaowang.com/attached/file/20170522/20170522185933_400.jpeg",
     * "activitySort":0,
     * "activityTitle":"你旅游我买单",
     * "activityType":0,
     * "activityUrl":"https://www.ruitaowang.com/wap/wx/login?fk=1-15-0-718",
     * "ctime":1495450727557,
     * "goodsId":0,
     * "mtime":1495461867633,
     * "rstatus":0
     * }
     * ],
     * "msg":"操作成功啦",
     * "records":5,
     * "title":"成功",
     * "total":1,
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/activities/preNextActivity"
     * }
     */
    @RequestMapping(value = "/api/activities/preNextActivity", method = RequestMethod.GET)
    public String listForOffice(Activity activity) {
        MsgOut o = MsgOut.success(activityService.selectForNextAndPre(activity));
        return this.renderJson(o);
    }

    private void setUserProfitNew(String orderSn, Long userId, Integer amount, Long consumerId, Long orderId, Integer profit, int orderType, byte profitType) {
        UserProfit userProfit = new UserProfit();
        userProfit.setOrderSn(orderSn);
        userProfit.setUserId(userId);
        userProfit.setAmount(amount);
        userProfit.setConsumerId(consumerId);
        userProfit.setOrderId(orderId);
        userProfit.setUserProfit(profit);
        userProfit.setOrderType((byte) orderType);
        userProfit.setProfitType(profitType);
        userProfitService.insert(userProfit);
    }

    @RequestMapping(value = "/api/ceshi", method = RequestMethod.GET)
    public void ceshi() throws UnknownHostException {
        InetAddress addr = InetAddress.getLocalHost();
        String ip=addr.getHostAddress().toString(); //获取本机ip
        String hostName=addr.getHostName().toString(); //获取本机计算机名称

        LOGGER.info("ip地址为：" + ip);
        LOGGER.info("计算机的名称为：" + hostName);
    }
}
